<comment>
# 组件注释
切片创建页面
</comment>
<template>
  <div class="sliceCreated">
    <!--todo 刷新 按钮根据页面状态判断 right-text 是否要为空串。以及各个板块是否要展示-->
    <van-nav-bar
      title="切片创建"
      left-text="返回"
      right-text="刷新"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />

    <result-show v-if="showStatus !== 'doing'" :status="showStatus" :reason="failedReason"></result-show>
    <!--手机号展示-->
    <div v-if="showStatus === 'doing' || showStatus === 'success'">
      <van-form>
        <van-field v-model="formData.MDN" name="手机号" label="手机号" />

        <van-field v-model="formData.dnnName" name="DNN名称" label="DNN名称" />
      </van-form>

      <div class="time-auto-add">
        {{ timeShow }}
      </div>

      <!--loading-->
      <div v-show="showStatus !== 'success'" style="margin-top: 20px">
        <van-loading size="24px" vertical>加载中...</van-loading>
      </div>
    </div>
    </div>
</template>

<script>
import { timeAddOneSecond } from '@/utils/commonUtils.js'
import resultShow from './components/resultShow'
import {getServTaskLogDetail, getSnssaiByMd, insertSnssaiByMdn} from "../../api/slice";
import {dealTime} from "../../utils/commonUtils";
import {Toast} from "vant";
export default {
  name: 'SliceCreated',
  components: {
    resultShow
  },
  data() {
    return {
      formData: {
        MDN: '',
        dnnName: ''
      },
      // 展示状态 doing. 开通中 success.开通成功 failed.开通失败 notExist.未开通
      showStatus: 'doing',
      timeShow: '00:00:00',
      autoAdd: null,
      failedReason: '',
      wsnbr: '',
      taskid: '',
      RNID: null,
      TNID: null,
      CNID: null,
      domainIsSuccess: {
        RN: false,
        CN: false,
        TN: true
      },
      failureReason: '',
      insertParams: {}
    }
  },
  props: {},
  watch: {},
  methods: {
    onClickLeft() {
      this.$router.push({
        path: '/slice'
      })
    },
    onClickRight() {
      this.getInfos()
    },
    // 时间自动增加
    timeAutoAdd() {
      this.autoAdd = setInterval(() => {
        this.timeShow = timeAddOneSecond(this.timeShow)
      }, 1000)
    },
    getInfos() {
      clearInterval(this.autoAdd)
      const param = {
        userData: {
          MDN: this.formData.MDN
        }
      }
      getSnssaiByMd(param).then(res => {
        // 判断状态
        const { dnnName, createTime } = res

        this.formData.dnnName = dnnName

        // 将毫秒转换成HH:mm:ss

        this.timeShow = dealTime(Number(createTime)).time
        // 开始计时
        this.timeAutoAdd()
        // 开始查询日志
        this.getServTaskLogDetail()
      })
    },
    initPage() {
      const { MDN, wsnbr, taskid, insertParams } = this.$route.query
      this.formData.MDN = MDN
      this.wsnbr = wsnbr
      this.taskid = taskid
      this.insertParams = insertParams

      this.getInfos()
    },

    // 查询日志
    getServTaskLogDetail() {
      const params = {
        wsnbr: this.wsnbr,
        taskid: this.taskid
      }
      // api/rest/worksheet/v1/5GSlice/getServTaskLogDetail
      getServTaskLogDetail(params).then(data => {
        let newSubTaskType = false
        let newExecstatus = true
        console.log('data', data)
        data.forEach((item, index) => {
          let { subTaskType } = item
          let { execstatus } = item

          if (subTaskType === 'sliceSign') {
            newSubTaskType = true

            if (+execstatus !== 0) {
              newExecstatus = false
            }
          }
        })

        if (newSubTaskType && newExecstatus) {
          if (this.taskid && this.taskid !== 'null') {
            // this.getSliceDataXXXXX()
            this.netWorkFlag()
            // this.translateFlag()
            this.coreFlag()
          }
        }
      })
    },
    netWorkFlag() {
      if (this.RNID) {
        clearInterval(this.RNID)
        this.RNID = null
      }
      this.RNID = setInterval(async () => {
        let data = await this.networkSliceCreate()
        console.log('data network', data)

        if (data === 'success') {
          clearInterval(this.RNID)
          this.RNID = null
          this.domainIsSuccess.RN = true
          this.successCase('RN')
        } else if (data === 'failure') {
          this.domainIsSuccess.RN = false
          this.failureCase()
        }
      }, 5000)
    },

    // 无线网子切片开通
    networkSliceCreate() {
      console.log('networkSliceCreate ~ 无线网子切片开通')
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // api/rest/worksheet/v1/5GSlice/getServTaskLogDetail
      return getServTaskLogDetail(params).then(async data => {
        if (data.length === 0) {
          return
        }
        let timeData = data.filter(item => {
          return item.subTaskType === 'rnResCreate'
        })

        if (timeData.length === 0) {
          return
        }

        console.log('timeData', timeData)
        if (
          timeData[timeData.length - 2] &&
          timeData[timeData.length - 2].execstatus &&
          timeData[timeData.length - 2].execstatus == 1
        ) {
          // this.domainIsSuccess.RN = false
          // this.failureCase()
          this.failureReason = timeData[timeData.length - 2].result
          return 'failure'
        }

        if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 0
        ) {
          return 'success'
        }
      })
    },

    // 核心网循环调
    coreFlag() {
      if (this.CNID) {
        clearInterval(this.CNID)
        this.CNID = null
      }
      this.CNID = setInterval(async () => {
        let data = await this.coreSliceCreate()

        if (data === 'success') {
          // 成功 清除不继续判断 置状态
          clearInterval(this.CNID)
          this.CNID = null
          this.domainIsSuccess.CN = true
          this.successCase('CN')
        } else if (data === 'failure') {
          // 失败 停止流程 置状态
          this.domainIsSuccess.CN = false
          this.failureCase()
        }
      }, 5000)
    },

    // 核心网子切片开通
    coreSliceCreate() {
      console.log('coreSliceCreate ~ 核心网子切片开通')
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // return this.$utils
      //   .doRequest('api/rest/worksheet/v1/5GSlice/getServTaskLogDetail', { ...params }, 'get')
      return getServTaskLogDetail(params).then(async data => {
        if (data.length === 0) {
          return
        }

        let timeData = data.filter(item => {
          return item.subTaskType === 'cnResCreate'
        })

        if (timeData.length === 0) {
          return
        }

        let isFinish = false

        if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 1
        ) {
          // this.domainIsSuccess.CN = false
          // this.failureCase()
          this.failureReason = timeData[timeData.length - 1].result
          return 'failure'
        } else if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 0
        ) {
          isFinish = true
        }

        // this.coreSliceResult = arr

        let flag = await this.isFinishCore()

        if (flag) {
          if (isFinish) {
            // clearInterval(this.CNID)
            // this.CNID = null
            // this.domainIsSuccess.CN = true
            // this.successCase('CN')

            return 'success'
          }
        }
      })
    },

    async isFinishCore() {
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // let res = await this.$utils.doRequest('api/rest/worksheet/v1/5GSlice/getServTaskLogDetail', { ...params }, 'get')
      let data = await getServTaskLogDetail(params)

      if (data.length === 0) {
        return
      }

      let timeData = data.filter(item => {
        return item.subTaskType === 'Ping'
      })
      console.log('timeData', timeData)

      return timeData.length > 0
    },

    successCase(type) {
      let obj = this.deepClone(this.domainIsSuccess)
      let flag = true
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          const element = obj[key]
          if (!element) {
            flag = element
          }
        }
      }

      if (flag) {
        this.clearInterVal()

        this.insertSnssaiByMdn2('1')
      }
    },

    deepClone(data) {
      return JSON.parse(JSON.stringify(data))
    },

    clearInterVal() {
      if (this.RNID) {
        clearInterval(this.RNID)
        this.RNID = null
      }
      if (this.TNID) {
        clearInterval(this.TNID)
        this.TNID = null
      }
      if (this.CNID) {
        clearInterval(this.CNID)
        this.CNID = null
      }
    },

    failureCase() {
      this.clearInterVal()

      Toast.clear()
      this.insertSnssaiByMdn2('0', this.failureReason)
    },

    insertSnssaiByMdn2(failStatus, reason) {
      const params = {...this.insertParams}
      params.snssaiData.snssaiStatus = failStatus
      params.snssaiData.failureCause = failStatus === '0' ? reason : ''

      // api/rest/worksheet/v1/5GSlice/insertSnssaiByMdn
      insertSnssaiByMdn(params).then(data => {
        this.$router.push({
          path: '/slice/create',
          query: { MDN: this.formData.MDN }
        })
      })
    },
  },
  computed: {},
  created() {},
  mounted() {
    this.initPage()
  },
  destroyed() {}
}
</script>

<style lang='scss' scoped>
.sliceCreated {
  .time-auto-add {
    width: 100%;
    font-size: 50px;
    font-weight: bold;
    padding: 20px 0;
    text-align: center;
  }
}
</style>
